package com.wang.store.controller;

import com.wang.store.controller.ex.FileSizeException;
import com.wang.store.controller.ex.FileTypeException;
import com.wang.store.controller.ex.FileUploadIOException;
import com.wang.store.entity.User;
import com.wang.store.service.IUserService;
import com.wang.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RestController  //@Controller+@ResponseBody
@RequestMapping("users")
public class UserController extends BaseController {
    @Autowired
    private IUserService iUserService;

    /**
     * *1.接收数据方式:请求处理方法的参数列表设置为pojo类型来接收前端的数据,
     * SpringBoot会将前端的url地址中的参数名和pojo类的属性名进行比较，
     * 如果这两个名称项目，则将值注入到pojo类中对应的属性上
     * @param user
     * @return
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        iUserService.reg(user);
        return  new JsonResult<>(OK) ;
    }


    /*//@ResponseBody 方法的结果以json的格式响应到前端
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        //创建响应结果的对象
        JsonResult<Void> result = new JsonResult<>();

        try {
            iUserService.reg(user);
            result.setState(200);
            result.setMessage("注册成功");
        } catch (UsernameDuplicateException e) {
            result.setState(4000);
            result.setMessage("用户名被占用");
        }catch (InsertException e){
            result.setState(5000);
            result.setMessage("注册时出现了未知的错误");

        }
        return result;
    }*/

    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = iUserService.login(username, password);
        //向session对象中完成数据的绑定的数据
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        System.out.println(getuidFromSession(session));
        System.out.println(getUsernameFromSession(session));
        return  new JsonResult<User>( OK,data);
    }

    @RequestMapping("change_password")
    public  JsonResult<Void> changePassword(String oldPassword,
                                            String newPassword,
                                            HttpSession session ){
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        iUserService.changePassword(uid,username,oldPassword,newPassword);
            return new  JsonResult<> (OK);
    }
    @RequestMapping("get_by_uid")
    public  JsonResult<User> getByUid(HttpSession session ){
        User data = iUserService.getByUid(getuidFromSession(session));
        return new  JsonResult<> (OK,data);
    }
    @RequestMapping("change_info")
    public  JsonResult<Void> changeInfo(HttpSession session,
                                        User user){
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        iUserService.ChangeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }
    //文件最大为10m
    public static final Integer AVATAR_MAX_SIZE =10*1024*1024;
    //文件类型
    public static  final List<String> AVATAR_TYPE=
            new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/gif");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/png");
    }


    @RequestMapping("change_avatar")
    public  JsonResult<String> changeAvatar(HttpSession session,
                                          MultipartFile file){
        if (file.getSize()>AVATAR_MAX_SIZE) {
            throw new FileSizeException("文件太大");
        }
        if (!AVATAR_TYPE.contains(file.getContentType())){
            throw new FileTypeException("文件类型异常");
        }
        //上传的文件 /upload/xx.jpg
        String path = session.getServletContext().getRealPath("upload");
        File dir = new File(path);
        if (!dir.exists()) {//检测目录是否存在
            dir.mkdirs(); //创建当前目录
        }
        //获取这个文件的名称UUID工具来生成一个新的字符串作为文件名
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i);
        String  filename= UUID.randomUUID().toString().toUpperCase()+substring;
        File dest = new File(dir, filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
        throw new FileUploadIOException("文件存的时候发生了异常");
        }
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        String avatar="/upload/"+filename;
        iUserService.ChangeAvatar(uid,avatar,username);
            return new  JsonResult<> (OK,avatar);
    }


}

